<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="ruleForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="pwd">
    <el-input v-model="ruleForm.pwd"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
  </el-form-item>
</el-form>
</template>
<script>
import { login } from '@/api'
export default {
  data () {
    return {
      ruleForm: {
        username: '',
        pwd: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.ruleForm).then(res => {
            if (res.data.code === '0') {
              // 存储用户信息
              localStorage.setItem('userInfo', JSON.stringify({
                userName: res.data.data.userName,
                avatar: res.data.data.avatar,
                role: res.data.data.role
              }))
              // 存储Token
              localStorage.setItem('accessToken', 'sdfadgasasga')
              // 跳转页面
              if (this.$route.params.path) {
                this.$message({
                  message: '登录成功',
                  duration: 1000,
                  type: 'warning',
                  onClose: () => {
                    this.$router.push(this.$route.params.path)
                  }
                })
              } else {
                this.$message({
                  message: '登录成功',
                  duration: 1000,
                  type: 'warning',
                  onClose: () => {
                    this.$router.push('/admin/dashBoard')
                  }
                })
              }
            }
          })
        } else {
          console.log('请按要求输入')
          return false
        }
      })
    }
  }
}
</script>
